package com.business.dynamic.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.business.common.dto.R;
import com.business.common.enums.BusinessExceptionEnum;
import com.business.common.enums.ErrorEnum;
import com.business.common.exception.BusinessException;
import com.business.common.exception.CustomException;
import com.business.common.utils.StrKit;
import com.business.dynamic.entity.DynamicComment;
import com.business.dynamic.service.DynamicCommentService;
import com.business.dynamic.utils.PageFactory;
import com.business.user.annotation.FrequentRequest;
import com.business.user.annotation.TokenPermission;
import com.business.user.entity.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 动态评论表: 后端controller类
 *
 * @author chenjiehong
 * @date 2019-11-29 15:15:38
 * @since 1.0
 */
@RestController
@RequestMapping(value = "/comment")
public class DynamicCommentController {


    @Autowired
    private DynamicCommentService dynamicCommentServiceImpl;


    /**
     * 新增动态评论表
     *
     * @param dynamicComment
     * @date 2019-11-29 15:15:38
     */
    @PostMapping("/add")
    @ResponseBody
    @TokenPermission
    @FrequentRequest(15)//控制频繁操作 一分钟内可以操作15次
    public R add(@RequestBody DynamicComment dynamicComment, UserDto userDto) {
        if (dynamicComment.getDynamicId() == null) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "dynamicId");
        }
        if (StrKit.isBlank(dynamicComment.getContent())) {
            throw new CustomException(ErrorEnum.PARAMS_LOSE, "content");
        }
        if (dynamicComment.getContent().length() > 500) {
            throw new BusinessException(BusinessExceptionEnum.COMMENT_LENGTH_ERROR);
        }
        dynamicComment.setUserId(userDto.getId());
        return R.success(dynamicCommentServiceImpl.add(dynamicComment));
    }


    /**
     * 分页查询动态评论表
     *
     * @param params
     * @date 2019-11-29 15:15:38
     */
    @PostMapping("/queryPage")
    @ResponseBody
    @TokenPermission(required = false)
    public R queryPage(@RequestBody JSONObject params, UserDto user) {
        Page<DynamicComment> page = new PageFactory<DynamicComment>().defaultPage(params);
        Integer dynamicId = params.getInteger("dynamicId");
        return R.success(dynamicCommentServiceImpl.queryPage(page, dynamicId, user.getId()));
    }


    /**
     * 删除动态评论表
     *
     * @param params
     * @date 2019-11-29 15:15:38
     */
    @PostMapping("/delete")
    @ResponseBody
    @TokenPermission
    @FrequentRequest(15)//控制频繁操作 一分钟内可以操作15次
    public R delete(@RequestBody JSONObject params) {
        Integer id = params.getInteger("id");
        return  R.success(dynamicCommentServiceImpl.delete(id));
    }


}